package com.qeeyou.apps.android.craftsman.fragment;


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.activity.home.CraftsmanActivity;
import com.qeeyou.apps.android.craftsman.activity.home.MasterDetailActivity;
import com.qeeyou.apps.android.craftsman.activity.home.SearchActivity;
import com.qeeyou.apps.android.craftsman.activity.login.LoginActivity;
import com.qeeyou.apps.android.craftsman.activity.me.SysMessageActivity;
import com.qeeyou.apps.android.craftsman.adapter.MasterAdapter;
import com.qeeyou.apps.android.craftsman.po.CommonInfo;
import com.qeeyou.apps.android.craftsman.po.LatestCommentInfo;
import com.qeeyou.apps.android.craftsman.po.LatestOrderInfo;
import com.qeeyou.apps.android.craftsman.po.MasterInfo;
import com.qeeyou.apps.android.craftsman.po_wrap.HomeInfo;
import com.qeeyou.apps.android.craftsman.service.AppService;
import com.qeeyou.apps.android.craftsman.service.SystemContext;
import com.qeeyou.apps.android.craftsman.view.BarActionButton;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xuchengxiong on 2017/12/14.
 */

public class HomeFragment extends BaseFragment {

    private BarActionButton btnSignIn;
    private BarActionButton btnMessage;
    private Button btnSearch;

    private TextView txtvLatestOrder;               //最新完成的订单信息
    private TextView txtvLatestComment;             //最新评论的订单信息
    private ImageView btnMore;
    private ListView lstvCraftsman;
    private MasterAdapter mAdapter;
    private String coordinates;                     //经纬度
    private CustomLoadingDialog mLoadingDialog;

    private Map<String, String> numberMap;

    public HomeFragment() {
        super(R.layout.fragment_home);
    }

    @Override
    protected void doOnCreate(Bundle savedInstanceState) {
        setView();
        setEvent();
        //加速数据
        loadData();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void setView() {
        btnSignIn = (BarActionButton) this.findViewById(R.id.btnSignIn4Home);
        btnMessage = (BarActionButton) this.findViewById(R.id.btnMessage4Home);
        txtvLatestOrder = (TextView) this.findViewById(R.id.txtvLatestOrder4Home);
        txtvLatestComment = (TextView) this.findViewById(R.id.txtvLatestComment4Home);
        btnSearch = (Button) this.findViewById(R.id.btnSearch4Home);
        btnMore = (ImageView) this.findViewById(R.id.btnMore4Home);
        lstvCraftsman = (ListView) this.findViewById(R.id.lstvCraftsman4Home);
    }

    private void setEvent() {

        mAdapter = new MasterAdapter(HomeFragment.this.getActivity(), null);
        lstvCraftsman.setAdapter(mAdapter);

        //师傅列表Item
        lstvCraftsman.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MasterInfo masterInfo = mAdapter.getItem(i);
                if (masterInfo != null) {
                    Intent intent = new Intent(HomeFragment.this.getActivity(), MasterDetailActivity.class);
                    intent.putExtra("masterInfo", masterInfo);
                    HomeFragment.this.getActivity().startActivity(intent);
                }
            }
        });

        //签到
        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String token = SystemContext.getInstance().getToken();
                if (token != null) {
                    new SignIn().execute();
                } else {
                    Toast.makeText(getContext(), "登录后才能签到成功!", Toast.LENGTH_SHORT).show();
                    //TODO -- 是否需要跳转登录页面
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(HomeFragment.this.getActivity(), LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            HomeFragment.this.getActivity().startActivity(intent);
                        }
                    }, 1000);
                }
            }
        });

        //消息
        btnMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String token = SystemContext.getInstance().getToken();
                if(token != null) {
                    Intent intent = new Intent(HomeFragment.this.getActivity(), SysMessageActivity.class);
                    HomeFragment.this.getActivity().startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "登录后才能查看系统消息!", Toast.LENGTH_SHORT).show();
                    //TODO -- 是否需要跳转登录页面
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(HomeFragment.this.getActivity(), LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            HomeFragment.this.getActivity().startActivity(intent);
                        }
                    }, 200);
                }

            }
        });

        //搜索
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO --搜索按钮点击事件
                Intent intent = new Intent(HomeFragment.this.getActivity(), SearchActivity.class);
                HomeFragment.this.getActivity().startActivity(intent);
            }
        });

        //更多师傅
        btnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String token = SystemContext.getInstance().getToken();
                if (token == null) {
                    Intent intent = new Intent(HomeFragment.this.getActivity(), LoginActivity.class);
                    HomeFragment.this.getActivity().startActivity(intent);
                } else {
                    Intent intent = new Intent(HomeFragment.this.getActivity(), CraftsmanActivity.class);
                    HomeFragment.this.getActivity().startActivity(intent);
                }

            }
        });

    }

    //加速数据
    private void loadData() {
        if(numberMap == null || numberMap.isEmpty()) {
            numberMap = new HashMap<String, String>();
            numberMap.put("0", "零");
            numberMap.put("1", "一");
            numberMap.put("2", "二");
            numberMap.put("3", "三");
            numberMap.put("4", "四");
            numberMap.put("5", "五");
            numberMap.put("6", "六");
            numberMap.put("7", "七");
            numberMap.put("8", "八");
            numberMap.put("9", "九");
            numberMap.put("10", "十");
        }
        //TODO -- 固定坐标
        this.coordinates = "121.360123,31.454778";
        String[] params = {this.coordinates};
        //获取首页所有信息
        new GetHomeWrapInfo().execute(params);
    }

    //获取首页信息
    class GetHomeWrapInfo extends AsyncTask<String, Void, HomeInfo> {

        public GetHomeWrapInfo() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(HomeFragment.this.getActivity());
            }
            mLoadingDialog.setMessage("正在获取首页信息...");
            mLoadingDialog.show();
        }

        @Override
        protected HomeInfo doInBackground(String... params) {
            HomeInfo homeInfo = new HomeInfo();
            //获取最新完成的订单信息
            Map<String, String> orderParamMap = new HashMap<String, String>();
            LatestOrderInfo orderInfo = AppService.getInstance().getLatestOrderInfo(orderParamMap);
            if(orderInfo != null) {
                homeInfo.setOrderInfo(orderInfo);
            }
            //获取最新评论的订单信息
            Map<String, String> commentParamMap = new HashMap<String, String>();
            LatestCommentInfo commentInfo = AppService.getInstance().getLatestCommentInfo(commentParamMap);
            if(commentInfo != null) {
                homeInfo.setCommentInfo(commentInfo);
            }
            //获取推荐师傅列表
            String coordinates = params[0];
            Map<String, String> mastersParamMap = new HashMap<String, String>();
            mastersParamMap.put("mycoo", coordinates);
            List<MasterInfo> masterList = AppService.getInstance().getRecommendMasterList(mastersParamMap);
            if(masterList != null) {
                homeInfo.setMasterList(masterList);
            }

            return homeInfo;
        }

        @Override
        protected void onPostExecute(HomeInfo resultInfo) {
            super.onPostExecute(resultInfo);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (resultInfo != null) {
                //显示主页信息
                showHomeInfo(resultInfo);
            } else {
                showHomeInfo(null);
            }
        }
    }

    //显示主页信息
    private void showHomeInfo(HomeInfo homeInfo) {
        if(homeInfo != null) {
            //显示最新订单信息
            if(homeInfo.getOrderInfo() != null) {
                String latestOrderStr = HomeFragment.this.getActivity().getResources().getString(R.string.home_latest_order_info);
                if(homeInfo.getOrderInfo().getOrderno() != null) {
                    latestOrderStr = latestOrderStr.replace("[XXXXXX]", homeInfo.getOrderInfo().getOrderno());
                }
                if(homeInfo.getOrderInfo().getOrderprice() != null) {
                    latestOrderStr = latestOrderStr.replace("[XXXX]", homeInfo.getOrderInfo().getOrderprice());
                }
                txtvLatestOrder.setText(latestOrderStr);
            } else {
                txtvLatestOrder.setText(R.string.home_latest_order_info);
            }
            //显示最新评论信息
            if(homeInfo.getCommentInfo() != null) {
                String lastestCommentStr = HomeFragment.this.getActivity().getResources().getString(R.string.home_latest_comment_info);
                if(homeInfo.getCommentInfo().getMastername() != null) {
                    lastestCommentStr = lastestCommentStr.replace("[XXX]", homeInfo.getCommentInfo().getMastername());
                }
                if(homeInfo.getCommentInfo().getCommentscore() != null
                        && !homeInfo.getCommentInfo().getCommentscore().trim().equalsIgnoreCase("")) {
                    String upperScore = homeInfo.getCommentInfo().getCommentscore().trim();
                    upperScore = numberMap.get(upperScore);
                    lastestCommentStr = lastestCommentStr.replace("[X]", upperScore);
                }
                txtvLatestComment.setText(lastestCommentStr);
            } else {
                txtvLatestComment.setText(R.string.home_latest_comment_info);
            }
            //显示推荐师傅列表
            if(homeInfo.getMasterList() != null) {
                mAdapter.setItems(homeInfo.getMasterList());
            } else {
                mAdapter.setItems(null);
            }
        } else {
            txtvLatestOrder.setText(R.string.home_latest_order_info);
            txtvLatestComment.setText(R.string.home_latest_comment_info);
            mAdapter.setItems(null);
        }
    }

    //首页签到
    class SignIn extends AsyncTask<String, Void, CommonInfo> {

        public SignIn() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(HomeFragment.this.getActivity());
            }
            mLoadingDialog.show();
        }

        @Override
        protected CommonInfo doInBackground(String... params) {
            CommonInfo resultInfo = AppService.getInstance().signedIn();
            return resultInfo;
        }

        @Override
        protected void onPostExecute(CommonInfo resultInfo) {
            super.onPostExecute(resultInfo);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (resultInfo != null && resultInfo.getStatus().equalsIgnoreCase("1")) {
                Toast.makeText(getContext(), resultInfo.getMessage(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), resultInfo.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }
}
